package file;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.*;
import java.util.zip.*;

public class FileManagerWindow extends JFrame {
    private JTree folderTree;
    private JTable fileList;
    private JTextField pathField;
    private JButton newFileButton;
    private JButton newFolderButton;
    private JButton deleteButton;
    private JButton copyButton;
    private JButton pasteButton;
    private JButton compressButton;
    private String currentPath = System.getProperty("user.home");
    private JTabbedPane documentTabbedPane;

    public FileManagerWindow() {
        setTitle("文件管理器");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initUI();
    }

    private void initUI() {
        // 文件夹树形结构导航栏
        folderTree = new JTree();
        JScrollPane treeScrollPane = new JScrollPane(folderTree);
        treeScrollPane.setPreferredSize(new Dimension(200, 800));
        add(treeScrollPane, BorderLayout.WEST);

        // 文件列表显示区
        fileList = new JTable(new FileTableModel());
        JScrollPane fileScrollPane = new JScrollPane(fileList);
        add(fileScrollPane, BorderLayout.CENTER);

        // 文档管理面板
        documentTabbedPane = new JTabbedPane();
        JScrollPane documentScrollPane = new JScrollPane(documentTabbedPane);
        documentScrollPane.setPreferredSize(new Dimension(800, 100));
        add(documentScrollPane, BorderLayout.SOUTH);

        // 操作按钮区
        JPanel buttonPanel = new JPanel();
        pathField = new JTextField(currentPath);
        pathField.setEditable(false);
        buttonPanel.add(pathField);

        newFileButton = new JButton("新建文件");
        newFolderButton = new JButton("新建文件夹");
        deleteButton = new JButton("删除");
        copyButton = new JButton("复制");
        pasteButton = new JButton("粘贴");
        compressButton = new JButton("压缩");
        JButton openFileButton = new JButton("打开文件"); // 添加打开文件按钮

        buttonPanel.add(newFileButton);
        buttonPanel.add(newFolderButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(copyButton);
        buttonPanel.add(pasteButton);
        buttonPanel.add(compressButton);
        buttonPanel.add(openFileButton); // 将打开文件按钮添加到按钮面板

        add(buttonPanel, BorderLayout.NORTH);

        // 添加按钮事件监听
        newFileButton.addActionListener(e -> createFile());
        newFolderButton.addActionListener(e -> createFolder());
        deleteButton.addActionListener(e -> deleteSelectedFile());
        copyButton.addActionListener(e -> copySelectedFile());
        pasteButton.addActionListener(e -> pasteFile());
        compressButton.addActionListener(e -> compressSelectedFile());
        openFileButton.addActionListener(e -> openFile()); // 添加打开文件按钮的事件监听

        // 初始化文件列表模型
        ((FileTableModel) fileList.getModel()).setDirectory(new File(currentPath));
    }

    private void createFile() {
        String fileName = JOptionPane.showInputDialog("请输入文件名");
        if (fileName != null && !fileName.isEmpty()) {
            File file = new File(currentPath + File.separator + fileName);
            try {
                if (file.createNewFile()) {
                    JOptionPane.showMessageDialog(this, "文件创建成功");
                    refreshFileList();
                } else {
                    JOptionPane.showMessageDialog(this, "文件已存在");
                }
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "文件创建失败：" + ex.getMessage());
            }
        }
    }

    private void createFolder() {
        String folderName = JOptionPane.showInputDialog("请输入文件夹名");
        if (folderName != null && !folderName.isEmpty()) {
            File folder = new File(currentPath + File.separator + folderName);
            if (folder.mkdir()) {
                JOptionPane.showMessageDialog(this, "文件夹创建成功");
                refreshFileList();
            } else {
                JOptionPane.showMessageDialog(this, "文件夹创建失败");
            }
        }
    }

    private void deleteSelectedFile() {
        int selectedRow = fileList.getSelectedRow();
        if (selectedRow != -1) {
            String fileName = fileList.getModel().getValueAt(selectedRow, 0).toString();
            File file = new File(currentPath + File.separator + fileName);
            if (file.delete()) {
                JOptionPane.showMessageDialog(this, "删除成功");
                refreshFileList();
            } else {
                JOptionPane.showMessageDialog(this, "删除失败");
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择一个文件或文件夹");
        }
    }

    private void copySelectedFile() {
        int selectedRow = fileList.getSelectedRow();
        if (selectedRow != -1) {
            String fileName = fileList.getModel().getValueAt(selectedRow, 0).toString();
            File file = new File(currentPath + File.separator + fileName);
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            Transferable transferable = new FileTransferable(file);
            ((Clipboard) clipboard).setContents(transferable, null);
            JOptionPane.showMessageDialog(this, "文件已复制到剪贴板");
        } else {
            JOptionPane.showMessageDialog(this, "请先选择一个文件或文件夹");
        }
    }

    private void pasteFile() {
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable transferable = clipboard.getContents(null);
        if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            try {
                java.util.List<File> droppedFiles = (java.util.List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
                for (File file : droppedFiles) {
                    File newFile = new File(currentPath + File.separator + file.getName());
                    if (!newFile.exists()) {
                        if (file.renameTo(newFile)) {
                            JOptionPane.showMessageDialog(this, "文件粘贴成功");
                            refreshFileList();
                        } else {
                            JOptionPane.showMessageDialog(this, "文件粘贴失败");
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "文件已存在");
                    }
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "粘贴失败：" + ex.getMessage());
            }
        } else {
            JOptionPane.showMessageDialog(this, "剪贴板中没有文件");
        }
    }

    private void compressSelectedFile() {
        int[] selectedRows = fileList.getSelectedRows();
        if (selectedRows.length > 0) {
            File[] files = new File[selectedRows.length];
            for (int i = 0; i < selectedRows.length; i++) {
                String fileName = fileList.getModel().getValueAt(selectedRows[i], 0).toString();
                files[i] = new File(currentPath + File.separator + fileName);
            }
            compressFiles(files);
        } else {
            JOptionPane.showMessageDialog(this, "请先选择一个或多个文件或文件夹");
        }
    }

    private void compressFiles(File[] files) {
        String zipFileName = JOptionPane.showInputDialog("请输入压缩文件名（包括.zip扩展名）");
        if (zipFileName != null && !zipFileName.isEmpty()) {
            File zipFile = new File(currentPath + File.separator + zipFileName);
            try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
                for (File file : files) {
                    if (file.isFile()) {
                        ZipEntry ze = new ZipEntry(file.getName());
                        zos.putNextEntry(ze);
                        try (FileInputStream fis = new FileInputStream(file)) {
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length = fis.read(buffer)) > 0) {
                                zos.write(buffer, 0, length);
                            }
                        }
                        zos.closeEntry();
                    } else if (file.isDirectory()) {
                        addDirToZip(file, file.getName(), zos);
                    }
                }
                JOptionPane.showMessageDialog(this, "文件压缩成功");
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "文件压缩失败：" + ex.getMessage());
            }
        }
    }
    private void openFile() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setMultiSelectionEnabled(true); // 允许选择多个文件
        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File[] selectedFiles = fileChooser.getSelectedFiles();
            for (File file : selectedFiles) {
                openDocument(file);
            }
        }
    }

    private void openDocument(File file) {
        try {
            JTextArea textArea = new JTextArea();
            textArea.read(new FileReader(file), null); // 读取文件内容到文本区域
            JScrollPane scrollPane = new JScrollPane(textArea);
            documentTabbedPane.addTab(file.getName(), scrollPane); // 为文件创建标签页
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "打开文件失败：" + ex.getMessage());
        }
    }
    private void addDirToZip(File dir, String baseName, ZipOutputStream zos) throws IOException {
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                String filePath = baseName + File.separator + file.getName();
                if (file.isFile()) {
                    ZipEntry ze = new ZipEntry(filePath);
                    zos.putNextEntry(ze);
                    try (FileInputStream fis = new FileInputStream(file)) {
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = fis.read(buffer)) > 0) {
                            zos.write(buffer, 0, length);
                        }
                    }
                    zos.closeEntry();
                } else if (file.isDirectory()) {
                    addDirToZip(file, filePath, zos);
                }
            }
        }
    }

    private void refreshFileList() {
        FileTableModel model = (FileTableModel) fileList.getModel();
        model.setDirectory(new File(currentPath));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new FileManagerWindow().setVisible(true));
    }
}